package cn.xfdzx.android.apps.shop.activity.ruzhu;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;

import java.io.File;
import java.io.IOException;
import java.net.Proxy;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import cn.xfdzx.android.apps.shop.R;
import cn.xfdzx.android.apps.shop.apps.Constants;
import cn.xfdzx.android.apps.shop.base.BaseMvpActivity;
import cn.xfdzx.android.apps.shop.bean.IdCardBeen;
import cn.xfdzx.android.apps.shop.bean.LicenseImgBeen;
import cn.xfdzx.android.apps.shop.bean.Ruzhu_StepBean;
import cn.xfdzx.android.apps.shop.bean.Store_ruzhuBean;
import cn.xfdzx.android.apps.shop.bean.UploadImgBeen;
import cn.xfdzx.android.apps.shop.contract.Store_InfoContract;
import cn.xfdzx.android.apps.shop.presenter.Store_InfoPresenter;
import cn.xfdzx.android.apps.shop.util.GlideEngine;
import cn.xfdzx.android.apps.shop.util.ShopCarPopupWindow;
import cn.xfdzx.android.apps.shop.util.UtilsLog;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static cn.xfdzx.android.apps.shop.apps.Constants.APP_TOKEN;

public class QualificationsActivity extends BaseMvpActivity<Store_InfoPresenter> implements Store_InfoContract.View {


    @BindView(R.id.ll_state)
    LinearLayout llState;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.tv_title_name)
    TextView tvTitleName;
    @BindView(R.id.sele_gerenmaijia)
    ImageView seleGerenmaijia;
    @BindView(R.id.getijingshang)
    ImageView getijingshang;
    @BindView(R.id.qiye)
    ImageView qiye;
    @BindView(R.id.ll_retail_shop_name)
    LinearLayout llRetailShopName;
    @BindView(R.id.tv_retail_qualifications_name)
    TextView tvRetailQualificationsName;
    @BindView(R.id.tv_found_address)
    TextView tvFoundAddress;
    @BindView(R.id.ll_address_shop_name)
    LinearLayout llAddressShopName;
    @BindView(R.id.tv_retail_shop_name)
    TextView tvRetailShopName;
    @BindView(R.id.ll_shop_photo)
    LinearLayout llShopPhoto;
    @BindView(R.id.sc_yingyezhizhao)
    ImageView scYingyezhizhao;
    @BindView(R.id.rl_shop_photo)
    RelativeLayout rlShopPhoto;
    @BindView(R.id.ett_zhucehao)
    EditText ettZhucehao;
    @BindView(R.id.ll_contacts_name)
    LinearLayout llContactsName;
    @BindView(R.id.shanghumingcheng)
    EditText shanghumingcheng;
    @BindView(R.id.ll)
    LinearLayout ll;
    @BindView(R.id.zhucedizhi)
    EditText zhucedizhi;
    @BindView(R.id.ll_invite_number)
    LinearLayout llInviteNumber;
    @BindView(R.id.fadingdbr)
    EditText fadingdbr;
    @BindView(R.id.ll_contacts_phone)
    LinearLayout llContactsPhone;
    @BindView(R.id.changqiyouxiao)
    ImageView changqiyouxiao;
    @BindView(R.id.ll_qixian)
    LinearLayout llQixian;
    @BindView(R.id.gudingyouxiao)
    ImageView gudingyouxiao;
    @BindView(R.id.kaishishijian)
    TextView kaishishijian;
    @BindView(R.id.jieshushijian)
    TextView jieshushijian;
    @BindView(R.id.ll_state_control_person)
    LinearLayout llStateControlPerson;
    @BindView(R.id.ett_supplement)
    EditText ettSupplement;
    @BindView(R.id.ll_supplement)
    LinearLayout llSupplement;
    @BindView(R.id.rl_state_control)
    RelativeLayout rlStateControl;
    @BindView(R.id.tv_yi_du)
    TextView tvYiDu;
    @BindView(R.id.hintzhucehao)
    TextView hintzhucehao;
    @BindView(R.id.hintshanghumingcheng)
    TextView hintshanghumingcheng;
    @BindView(R.id.hintfadingdbr)
    TextView hintfadingdbr;
    @BindView(R.id.hintbuchongshuoming)
    TextView hintbuchongshuoming;
    @BindView(R.id.hintchange)
    TextView hintchange;
    @BindView(R.id.time)
    LinearLayout time;

    private ShopCarPopupWindow yearPopupWindow;
    //用来存储年月日
    int year, month, day;
    //存储页面上的日期选择器
    DatePicker datePicker;
    private String nyr_start = "";
    private String validTerm = "";//有效期
    private String nyr_end = "";
    private Calendar calendar;
    private String subject_type = "";
    private String storeid;
    protected Handler handler = new Handler();
    private String store_mentouzhao = "";
    private String kaishiri;
    private int temp = 0;
    private int temps = 0;
    private int t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, t8 = 0, t9 = 0, t10 = 0;

public Context mContext;
    @Override
    public int getLayoutId() {
        return R.layout.activity_qualifications;
    }

    @Override
    public void initView() {

        mPresenter = new Store_InfoPresenter();
        mPresenter.attachView(this);

        mPresenter.getStep_Ruzhu("two");
        mContext=this;

    }

    @Override
    public void getStateType(Store_ruzhuBean bean) {
        Log.e("ruzhubea", bean.getMsg() + bean.getStatus() + bean.getData().toString());
    }


    @Override
    public void getRuzhuStep(Ruzhu_StepBean bean) {
        Intent intent = getIntent();
        storeid = intent.getStringExtra("stoid");
        Log.e("bless", bean.getData().getSubject_type() + "");
        if (bean.getData().getSubject_type().equals("2500") == false) {
            setText(bean);
        } else {
            seleGerenmaijia.setImageResource(R.drawable.circle_ok);
            qiye.setImageResource(R.drawable.circle);
            getijingshang.setImageResource(R.drawable.circle);
            llStateControlPerson.setVisibility(View.GONE);
            rlStateControl.setVisibility(View.VISIBLE);
            hintchange.setVisibility(View.GONE);
            subject_type = "2500";
        }


    }

    private void setText(Ruzhu_StepBean bean) {
        ChangeSubject(bean.getData().getSubject_type(), "");
        RoundedCorners roundedCorners = new RoundedCorners(10);
        //通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
        RequestOptions options = RequestOptions.bitmapTransform(roundedCorners);
        Glide.with(this).load(bean.getData().getStore_qualifications_img()).apply(options.transform(new CenterCrop(), roundedCorners)).into(scYingyezhizhao);
        store_mentouzhao = bean.getData().getStore_qualifications_img();

        ettZhucehao.setText(bean.getData().getStore_qualifications_num());
        shanghumingcheng.setText(bean.getData().getStore_qualifications_name());
        zhucedizhi.setText(bean.getData().getStore_qualifications_address());
        fadingdbr.setText(bean.getData().getStore_master());
        ChangeSubject("", bean.getData().getStore_qualifications_expire());
        kaishishijian.setText(bean.getData().getStore_qualifications_start());
        jieshushijian.setText(bean.getData().getStore_qualifications_expire());

    }

    private void ChangeSubject(String sub, String type) {
        if (sub.equals("4")) {
            seleGerenmaijia.setImageResource(R.drawable.circle);
            qiye.setImageResource(R.drawable.circle);
            getijingshang.setImageResource(R.drawable.circle_ok);
            llStateControlPerson.setVisibility(View.VISIBLE);
            rlStateControl.setVisibility(View.GONE);
            hintchange.setVisibility(View.GONE);
            subject_type = "4";

            temp = 1;
        } else if (sub.equals("2")) {
            seleGerenmaijia.setImageResource(R.drawable.circle);
            qiye.setImageResource(R.drawable.circle_ok);
            getijingshang.setImageResource(R.drawable.circle);
            llStateControlPerson.setVisibility(View.VISIBLE);
            rlStateControl.setVisibility(View.GONE);
            hintchange.setVisibility(View.GONE);
            subject_type = "2";
            temp = 2;
        } else if (sub.equals("2500")) {
            seleGerenmaijia.setImageResource(R.drawable.circle_ok);
            qiye.setImageResource(R.drawable.circle);
            getijingshang.setImageResource(R.drawable.circle);
            llStateControlPerson.setVisibility(View.GONE);
            rlStateControl.setVisibility(View.VISIBLE);
            hintchange.setVisibility(View.GONE);
            subject_type = "2500";

            temp = 3;

        }
        if (type.equals("长期") || type == null) {
            time.setVisibility(View.GONE);
            changqiyouxiao.setImageResource(R.drawable.circle_ok);
            gudingyouxiao.setImageResource(R.drawable.circle);
            temps = 1;
        } else {
            time.setVisibility(View.VISIBLE);
            changqiyouxiao.setImageResource(R.drawable.circle);
            gudingyouxiao.setImageResource(R.drawable.circle_ok);
            temps = 2;
        }

    }

    @Override
    public void oneLicenseImgSuccess(LicenseImgBeen bean) {
        ettZhucehao.setText(bean.getData().getCertNo());
        shanghumingcheng.setText(bean.getData().getName());
        zhucedizhi.setText(bean.getData().getAddress());
        fadingdbr.setText(bean.getData().getLegalRepName());
        validTerm = bean.getData().getValidTerm();
        ValidChange(validTerm);
    }

    @Override
    public void onIdCardSuccess(IdCardBeen bean) {
    }

    @Override
    public void onIdCardSuccessguanli(IdCardBeen bean) {

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void onError(Throwable throwable) {

    }

    private void ValidChange(String validTerm) {
        //2017年02月07日至2037年02月06日
        String[] splitAddress = validTerm.split("至");
        String kaishinian = splitAddress[0].replaceAll("年", "-");
        String kaishiyue = kaishinian.replaceAll("月", "-");
        String kaishiri = kaishiyue.replaceAll("日", "");
        kaishishijian.setText(kaishiri);
        kaishishijian.setTextColor(getResources().getColor(R.color.color_333333));
        if (validTerm.contains("年")) {
            String jieshunian = splitAddress[1].replaceAll("年", "-");
            String jieshuyue = jieshunian.replaceAll("月", "-");
            String jieshuri = jieshuyue.replaceAll("日", "");
            jieshushijian.setText(jieshuri);
            jieshushijian.setTextColor(getResources().getColor(R.color.color_333333));
        }


    }

    @OnClick({R.id.iv_back, R.id.sele_gerenmaijia, R.id.getijingshang, R.id.qiye, R.id.changqiyouxiao, R.id.gudingyouxiao, R.id.kaishishijian, R.id.jieshushijian, R.id.tv_yi_du, R.id.sc_yingyezhizhao})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.sele_gerenmaijia:
                seleGerenmaijia.setImageResource(R.drawable.circle_ok);
                qiye.setImageResource(R.drawable.circle);
                getijingshang.setImageResource(R.drawable.circle);
                llStateControlPerson.setVisibility(View.GONE);
                rlStateControl.setVisibility(View.VISIBLE);
                subject_type = "2500";
                hintchange.setVisibility(View.GONE);
                temp = 1;

                break;
            case R.id.getijingshang:
                seleGerenmaijia.setImageResource(R.drawable.circle);
                qiye.setImageResource(R.drawable.circle);
                getijingshang.setImageResource(R.drawable.circle_ok);
                llStateControlPerson.setVisibility(View.VISIBLE);
                rlStateControl.setVisibility(View.GONE);
                subject_type = "4";
                hintchange.setVisibility(View.GONE);
                temp = 2;
                break;
            case R.id.qiye:
                seleGerenmaijia.setImageResource(R.drawable.circle);
                qiye.setImageResource(R.drawable.circle_ok);
                getijingshang.setImageResource(R.drawable.circle);
                llStateControlPerson.setVisibility(View.VISIBLE);
                rlStateControl.setVisibility(View.GONE);
                subject_type = "2";
                hintchange.setVisibility(View.GONE);
                temp = 3;
                break;
            case R.id.changqiyouxiao:
                time.setVisibility(View.GONE);
                changqiyouxiao.setImageResource(R.drawable.circle_ok);
                gudingyouxiao.setImageResource(R.drawable.circle);
                temps = 1;
                break;
            case R.id.gudingyouxiao:
                time.setVisibility(View.VISIBLE);
                changqiyouxiao.setImageResource(R.drawable.circle);
                gudingyouxiao.setImageResource(R.drawable.circle_ok);
                temps = 2;
                break;
            case R.id.kaishishijian:
                popupWindow(1);

                break;
            case R.id.jieshushijian:
                popupWindow(2);

                break;
            case R.id.tv_yi_du:
                if (subject_type.equals("2500") == false) {
                    if (temp == 0) {
                        hintchange.setVisibility(View.VISIBLE);
                    } else {
                        hintchange.setVisibility(View.INVISIBLE);
                        t1 = 1;
                    }
                    if (store_mentouzhao.equals("") == false) {
                        t2 = 1;
                    }
                    if (ettZhucehao.getText().toString() == null || ettZhucehao.getText().toString().equals("")) {
                        hintzhucehao.setVisibility(View.VISIBLE);
                    } else {
                        hintzhucehao.setVisibility(View.INVISIBLE);
                        t3 = 1;
                    }
                    if (shanghumingcheng.getText().toString() == null || shanghumingcheng.getText().toString().equals("")) {
                        hintshanghumingcheng.setVisibility(View.VISIBLE);
                    } else {
                        hintshanghumingcheng.setVisibility(View.INVISIBLE);
                        t4 = 1;
                    }
                    if (fadingdbr.getText().toString().equals("") || fadingdbr.getText().toString() == null) {
                        hintfadingdbr.setVisibility(View.VISIBLE);
                    } else {
                        hintfadingdbr.setVisibility(View.INVISIBLE);
                        t5 = 1;
                    }
                    if (temps != 0) {
                        t6 = 1;
                    }
                    if (kaishishijian.getText().toString().equals("") || kaishishijian.getText().toString() == null) {
                        t7 = 0;
                    } else {
                        t7 = 1;
                    }
                    if (jieshushijian.getText().toString().equals("") || jieshushijian.getText().toString() == null) {
                        t8 = 0;
                    } else {
                        t8 = 1;
                    }
                    if (t1 == 1 && t2 == 1 && t3 == 1 && t4 == 1 && t5 == 1 && t6 == 1 && t7 == 1 && t8 == 1) {
                        HashMap<String, Object> map = new HashMap<>();
                        map.put("step", "two");
                        map.put("store_id", storeid);
                        map.put("subject_type", subject_type);
                        map.put("store_qualifications_img", store_mentouzhao);
                        map.put("store_qualifications_num", ettZhucehao.getText());
                        map.put("store_qualifications_name", shanghumingcheng.getText());
                        map.put("store_qualifications_address", zhucedizhi.getText());
                        map.put("store_master", fadingdbr.getText());
                        map.put("store_qualifications_start", kaishishijian.getText());
                        map.put("store_qualifications_expire", jieshushijian.getText());
                        Log.e("ceasd", map.toString());
                        mPresenter.getState_Ruzhu(map);
                        Intent intent = new Intent(this, InformationActivity.class);
                        startActivity(intent);
                    } else {
                        Toast.makeText(this, "请确认信息输入完整后提交！", Toast.LENGTH_SHORT).show();
                    }


                } else {
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("step", "two");
                    map.put("store_id", storeid);
                    map.put("subject_type", subject_type);
                    map.put("business_addition_msg", ettSupplement.getText());

                    mPresenter.getState_Ruzhu(map);
                    Intent intent = new Intent(this, InformationActivity.class);
                    startActivity(intent);
                }

                break;

            case R.id.sc_yingyezhizhao:
                selectImage(scYingyezhizhao);
                break;
            default:
                break;
        }
    }

    private void editListen(EditText ett, TextView textView) {

        ett.addTextChangedListener(new TextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {

                if (s.length() >= 1) {
                    textView.setVisibility(View.GONE);
                } else {
                    textView.setVisibility(View.VISIBLE);
                }
            }

        });
    }

    private void popupWindow(int flat) {
        yearPopupWindow = new ShopCarPopupWindow(this, R.layout.datepicker);


        datePicker = (DatePicker) findViewById(R.id.datePickerView);
        //获取当前日期
        calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH);
        day = calendar.get(Calendar.DAY_OF_MONTH);
        if (flat == 1) {
            new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {

                @Override
                public void onDateSet(DatePicker view, int year, int month, int day) {
                    nyr_start = year + "-" + month + "-" + day;
                    kaishishijian.setText(nyr_start);
                    kaishishijian.setTextColor(getResources().getColor(R.color.color_333333));
                }
            }, year, month, day).show(); //后三个参数相当于初始化
        } else {
            new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {

                @Override
                public void onDateSet(DatePicker view, int year, int month, int day) {
                    nyr_end = year + "-" + month + "-" + day;
                    jieshushijian.setText(nyr_end);
                    jieshushijian.setTextColor(getResources().getColor(R.color.color_333333));
                }
            }, year, month, day).show(); //后三个参数相当于初始化
        }


    }

    public void selectImage(ImageView imageView) {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage()).maxSelectNum(1)
                .loadImageEngine(GlideEngine.createGlideEngine())
                .minSelectNum(1).imageSpanCount(4)
                .selectionMode(PictureConfig.SINGLE)
                .compress(true)
                .minimumCompressSize(1000)
                .compressQuality(60)
                .isCamera(true)
                .previewImage(true)
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(List<LocalMedia> result) {
                        // onResult Callback
                        if (result.size() != 0) {
                            UtilsLog.error("dizhi", result.get(0).getCompressPath());
//                                    new File(result.get(0).getPath())
//                                    mPresenter.upload(new File(result.get(0).getPath()));
                            showLoading();
                            upLoadFiles(Constants.BASE_URL + "/addons/shimmer_liveshop/index.php/api/6/3/plugin/merch/common/apply/uploadImg", new File(result.get(0).getCompressPath()), new XFDShopInActivity.ConnectListener() {
                                @Override
                                public void connectSuccess(String result) {
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            hideLoading();
                                            try {
                                                Gson gson = new Gson();
                                                UploadImgBeen uploadImgBeen = gson.fromJson(result, UploadImgBeen.class);
                                                if (uploadImgBeen.getErrno().equals("200")) {

                                                    RoundedCorners roundedCorners = new RoundedCorners(10);
                                                    //通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
                                                    RequestOptions options = RequestOptions.bitmapTransform(roundedCorners);
                                                    Glide.with(mContext).load(uploadImgBeen.getData().getSrc()).apply(options.transform(new CenterCrop(), roundedCorners)).into(imageView);
                                                    if (imageView == scYingyezhizhao) {

                                                        store_mentouzhao = uploadImgBeen.getData().getSrc();
                                                        mPresenter.licenseImg(store_mentouzhao);

                                                    }

                                                } else {
                                                    Toast.makeText(mContext, uploadImgBeen.getMessage(), Toast.LENGTH_SHORT).show();
                                                }
                                            } catch (Exception e) {
                                                Toast.makeText(mContext, "上传失败", Toast.LENGTH_SHORT).show();

                                            }
                                        }
                                    });

                                }

                                @Override
                                public void connectFailed(String error) {
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            hideLoading();

                                        }
                                    });
                                }
                            });
                        }
                    }

                    @Override
                    public void onCancel() {
                        // onCancel Callback
                    }
                });
    }

    public void upLoadFiles(final String url, File file,
                            final XFDShopInActivity.ConnectListener connectListener) {
        OkHttpClient okHttpClient = new OkHttpClient.Builder().proxy(Proxy.NO_PROXY).connectTimeout(60 * 1000, TimeUnit.MILLISECONDS)
                .readTimeout(5 * 60 * 1000, TimeUnit.MILLISECONDS)
                .writeTimeout(5 * 60 * 1000, TimeUnit.MILLISECONDS)
                .build();
        MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder();
        multipartBodyBuilder.setType(MultipartBody.FORM);
        //遍历map中所有参数到builder
        multipartBodyBuilder.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/png"), file));
        //构建请求体
        RequestBody requestBody = multipartBodyBuilder.build();
        Request.Builder RequestBuilder = new Request.Builder();
        RequestBuilder.url(url);// 添加URL地址
        RequestBuilder.post(requestBody);
        RequestBuilder.addHeader("Authori-zation", "Bearer " + APP_TOKEN);
        Request request = RequestBuilder.build();

        final Call call = okHttpClient.newCall(request);
        //异步get请求
        call.enqueue(new Callback() {
                         @Override
                         public void onFailure(Call call, IOException e) {
                             connectListener.connectFailed(e.toString());
                             UtilsLog.error("错误", e.toString());
                         }

                         @Override
                         public void onResponse(Call call, Response response) throws IOException {
                             String result = response.body().string();
                             connectListener.connectSuccess(result);
                             UtilsLog.error("成功", result);
                         }
                     }
        );
    }

}